<template>
  <div class="dashboard-container">
      <!-- 欢迎区域 -->
      <div class="welcome-section">
        <el-card class="welcome-card">
          <div class="welcome-content">
            <div class="welcome-info">
              <h2>欢迎回来，{{ user?.username || user?.email }}！</h2>
              <p class="welcome-desc">
                您当前的角色是 <el-tag :type="getRoleTagType(user?.role)">{{ getRoleLabel(user?.role) }}</el-tag>
              </p>
              <p class="welcome-time">{{ getCurrentTime() }}</p>
            </div>
            <div class="welcome-avatar">
              <el-avatar :size="60" :src="user?.profile?.avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 统计卡片 -->
      <div class="stats-section">
        <el-row :gutter="20">
          <el-col :xs="12" :sm="12" :md="6" v-for="stat in statsCards" :key="stat.key">
            <el-card class="stats-card" shadow="hover">
              <div class="stats-content">
                <div class="stats-icon" :style="{ backgroundColor: stat.color + '20', color: stat.color }">
                  <el-icon><component :is="stat.icon" /></el-icon>
                </div>
                <div class="stats-info">
                  <div class="stats-value">{{ stat.value }}</div>
                  <div class="stats-label">{{ stat.label }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 快捷操作 -->
      <div class="quick-actions-section">
        <el-card>
          <template #header>
            <div class="card-header">
              <el-icon><Operation /></el-icon>
              <span>快捷操作</span>
            </div>
          </template>
          <el-row :gutter="16">
            <el-col :xs="12" :sm="8" :md="6" v-for="action in quickActions" :key="action.key">
              <div
                class="quick-action-item"
                @click="handleQuickAction(action)"
                v-if="action.roles.includes(user?.role)"
              >
                <div class="action-icon">
                  <el-icon><component :is="action.icon" /></el-icon>
                </div>
                <div class="action-content">
                  <h4>{{ action.title }}</h4>
                  <p>{{ action.description }}</p>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <!-- 最近活动 -->
      <el-row :gutter="20" class="activity-section">
        <!-- 最近批次 -->
        <el-col :xs="24" :md="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <el-icon><List /></el-icon>
                <span>最近批次</span>
                <el-button text type="primary" @click="goToBatches">查看全部</el-button>
              </div>
            </template>
            <div v-loading="batchesLoading">
              <div v-if="recentBatches.length === 0" class="empty-state">
                <el-empty description="暂无批次数据" :image-size="100" />
              </div>
              <div v-else>
                <div
                  v-for="batch in recentBatches"
                  :key="batch._id"
                  class="batch-item"
                  @click="goToBatchDetail(batch._id)"
                >
                  <div class="batch-info">
                    <div class="batch-name">{{ batch.name }}</div>
                    <div class="batch-meta">
                      <el-tag size="small" :type="getStatusTagType(batch.status)">
                        {{ getStatusLabel(batch.status) }}
                      </el-tag>
                      <span class="batch-variety">{{ batch.variety }}</span>
                    </div>
                    <div class="batch-time">{{ formatTime(batch.createdAt) }}</div>
                  </div>
                  <el-icon class="batch-arrow"><ArrowRight /></el-icon>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 系统通知 -->
        <el-col :xs="24" :md="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <el-icon><Bell /></el-icon>
                <span>系统通知</span>
              </div>
            </template>
            <div class="notifications">
              <div v-if="notifications.length === 0" class="empty-state">
                <el-empty description="暂无通知" :image-size="100" />
              </div>
              <div v-else>
                <div
                  v-for="notification in notifications"
                  :key="notification.id"
                  class="notification-item"
                >
                  <div class="notification-content">
                    <div class="notification-title">{{ notification.title }}</div>
                    <div class="notification-desc">{{ notification.content }}</div>
                    <div class="notification-time">{{ notification.time }}</div>
                  </div>
                  <el-badge :is-dot="!notification.read" class="notification-badge" />
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 数据概览和图表区域 -->
      <el-row :gutter="20" class="charts-section">
        <!-- 批次状态分布 -->
        <el-col :xs="24" :md="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <el-icon><PieChart /></el-icon>
                <span>批次状态分布</span>
              </div>
            </template>
            <div class="status-chart">
              <div v-for="status in statusDistribution" :key="status.name" class="status-item">
                <div class="status-bar">
                  <div 
                    class="status-progress" 
                    :style="{ 
                      width: status.percentage + '%', 
                      backgroundColor: status.color 
                    }"
                  ></div>
                </div>
                <div class="status-info">
                  <span class="status-name">{{ status.label }}</span>
                  <span class="status-count">{{ status.count }}</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 工作台 -->
        <el-col :xs="24" :md="12">
          <el-card>
            <template #header>
              <div class="card-header">
                <el-icon><Monitor /></el-icon>
                <span>我的工作台</span>
              </div>
            </template>
            <div class="workspace">
              <div v-if="user?.role === 'farmer'" class="workspace-section">
                <h4>茶农工作台</h4>
                <div class="workspace-items">
                  <div class="workspace-item" @click="router.push('/batches/create')">
                    <el-icon><Plus /></el-icon>
                    <span>创建新批次</span>
                  </div>
                  <div class="workspace-item" @click="router.push('/batches')">
                    <el-icon><Coffee /></el-icon>
                    <span>管理我的批次</span>
                  </div>
                </div>
              </div>
              
              <div v-if="user?.role === 'logistics'" class="workspace-section">
                <h4>物流工作台</h4>
                <div class="workspace-items">
                  <div class="workspace-item" @click="router.push('/batches?status=production')">
                    <el-icon><Van /></el-icon>
                    <span>待运输批次</span>
                  </div>
                  <div class="workspace-item" @click="router.push('/batches?status=logistics')">
                    <el-icon><Clock /></el-icon>
                    <span>运输中批次</span>
                  </div>
                </div>
              </div>
              
              <div v-if="user?.role === 'merchant'" class="workspace-section">
                <h4>商家工作台</h4>
                <div class="workspace-items">
                  <div class="workspace-item" @click="router.push('/batches?status=logistics')">
                    <el-icon><Shop /></el-icon>
                    <span>待入库批次</span>
                  </div>
                  <div class="workspace-item" @click="router.push('/batches?status=sales')">
                    <el-icon><ShoppingCart /></el-icon>
                    <span>销售中批次</span>
                  </div>
                </div>
              </div>

              <div v-if="user?.role === 'admin'" class="workspace-section">
                <h4>管理员工作台</h4>
                <div class="workspace-items">
                  <div class="workspace-item" @click="router.push('/users')">
                    <el-icon><UserFilled /></el-icon>
                    <span>用户管理</span>
                  </div>
                  <div class="workspace-item" @click="router.push('/statistics')">
                    <el-icon><DataAnalysis /></el-icon>
                    <span>数据统计</span>
                  </div>
                </div>
              </div>

              <!-- 通用功能 -->
              <div class="workspace-section">
                <h4>通用功能</h4>
                <div class="workspace-items">
                  <div class="workspace-item" @click="router.push('/trace')">
                    <el-icon><Search /></el-icon>
                    <span>溯源查询</span>
                  </div>
                  <div class="workspace-item" @click="router.push('/profile')">
                    <el-icon><User /></el-icon>
                    <span>个人中心</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { apiMethods } from '@/api'
import { ElMessage } from 'element-plus'
import {
  User,
  Operation,
  List,
  Bell,
  ArrowRight,
  Coffee,
  Van,
  Shop,
  DataAnalysis,
  Plus,
  Search,
  UserFilled,
  PieChart,
  Monitor,
  Clock,
  ShoppingCart
} from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

// 计算属性
const user = computed(() => authStore.user)

// 状态
const batchesLoading = ref(false)
const recentBatches = ref([])
const notifications = ref([
  {
    id: 1,
    title: '系统更新通知',
    content: '系统将于今晚10:00-12:00进行维护升级',
    time: '2小时前',
    read: false
  },
  {
    id: 2,
    title: '新功能上线',
    content: '批次统计图表功能已上线，欢迎体验',
    time: '1天前',
    read: true
  }
])

// 统计数据
const stats = ref({
  batches: 0,
  logistics: 0,
  sales: 0,
  views: 0
})

// 统计卡片
const statsCards = computed(() => {
  const cards = []
  
  if (['farmer', 'admin'].includes(user.value?.role)) {
    cards.push({
      key: 'batches',
      label: user.value?.role === 'farmer' ? '我的批次' : '总批次数',
      value: stats.value.batches || 0,
      icon: 'Coffee',
      color: '#67C23A'
    })
  }
  
  if (['logistics', 'admin'].includes(user.value?.role)) {
    cards.push({
      key: 'logistics',
      label: '物流记录',
      value: stats.value.logistics || 0,
      icon: 'Van',
      color: '#E6A23C'
    })
  }
  
  if (['merchant', 'admin'].includes(user.value?.role)) {
    cards.push({
      key: 'sales',
      label: '销售记录',
      value: stats.value.sales || 0,
      icon: 'Shop',
      color: '#409EFF'
    })
  }
  
  // 所有用户都显示查询统计
  cards.push({
    key: 'views',
    label: '查询次数',
    value: stats.value.views || Math.floor(Math.random() * 200) + 50, // 模拟数据
    icon: 'DataAnalysis',
    color: '#F56C6C'
  })
  
  return cards
})

// 状态分布数据
const statusDistribution = computed(() => {
  const statusData = [
    { name: 'created', label: '已创建', count: 8, color: '#909399' },
    { name: 'production', label: '生产中', count: 12, color: '#E6A23C' },
    { name: 'logistics', label: '运输中', count: 6, color: '#409EFF' },
    { name: 'sales', label: '销售中', count: 15, color: '#67C23A' },
    { name: 'consumed', label: '已消费', count: 3, color: '#F56C6C' }
  ]
  
  const total = statusData.reduce((sum, item) => sum + item.count, 0)
  
  return statusData.map(item => ({
    ...item,
    percentage: total > 0 ? Math.round((item.count / total) * 100) : 0
  }))
})

// 快捷操作
const quickActions = computed(() => [
  {
    key: 'create-batch',
    title: '创建批次',
    description: '创建新的茶叶批次',
    icon: 'Plus',
    roles: ['farmer', 'admin'],
    action: () => router.push('/batches/create')
  },
  {
    key: 'batch-list',
    title: '批次管理',
    description: '查看和管理批次',
    icon: 'Coffee',
    roles: ['farmer', 'logistics', 'merchant', 'admin'],
    action: () => router.push('/batches')
  },
  {
    key: 'trace-query',
    title: '溯源查询',
    description: '查询茶叶溯源信息',
    icon: 'Search',
    roles: ['farmer', 'logistics', 'merchant', 'consumer', 'admin'],
    action: () => router.push('/trace')
  },
  {
    key: 'user-manage',
    title: '用户管理',
    description: '管理系统用户',
    icon: 'UserFilled',
    roles: ['admin'],
    action: () => router.push('/users')
  }
])

// 方法
const getCurrentTime = () => {
  const now = new Date()
  const hour = now.getHours()
  
  let greeting = ''
  if (hour < 6) greeting = '深夜好'
  else if (hour < 9) greeting = '早上好'
  else if (hour < 12) greeting = '上午好'
  else if (hour < 14) greeting = '中午好'
  else if (hour < 18) greeting = '下午好'
  else if (hour < 22) greeting = '晚上好'
  else greeting = '夜深了'
  
  return `${greeting}，今天是 ${now.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric',
    weekday: 'long'
  })}`
}

const getRoleLabel = (role) => {
  const roleMap = {
    farmer: '茶农',
    logistics: '物流方',
    merchant: '商家',
    consumer: '消费者',
    admin: '管理员'
  }
  return roleMap[role] || role
}

const getRoleTagType = (role) => {
  const typeMap = {
    farmer: 'success',
    logistics: 'warning',
    merchant: 'info',
    consumer: 'primary',
    admin: 'danger'
  }
  return typeMap[role] || 'primary'
}

const getStatusLabel = (status) => {
  const statusMap = {
    created: '已创建',
    production: '生产中',
    logistics: '运输中',
    sales: '销售中',
    consumed: '已消费'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const typeMap = {
    created: 'info',
    production: 'warning',
    logistics: 'primary',
    sales: 'success',
    consumed: 'info'
  }
  return typeMap[status] || 'info'
}

const formatTime = (timeStr) => {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now - time
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`
  
  return time.toLocaleDateString('zh-CN')
}

const handleQuickAction = (action) => {
  action.action()
}

const goToBatches = () => {
  router.push('/batches')
}

const goToBatchDetail = (batchId) => {
  router.push(`/batches/${batchId}`)
}

const loadRecentBatches = async () => {
  try {
    batchesLoading.value = true
    const response = await apiMethods.batches.getList({
      page: 1,
      limit: 5
    })
    
    if (response.data.success) {
      recentBatches.value = response.data.data.list
    }
  } catch (error) {
    console.error('加载最近批次失败:', error)
  } finally {
    batchesLoading.value = false
  }
}

const loadStats = async () => {
  try {
    // 加载批次统计
    const statsResponse = await apiMethods.batches.getStats()
    if (statsResponse.data.success) {
      const batchStats = statsResponse.data.data.stats
      
      // 更新统计数据
      stats.value.batches = batchStats.total || 0
      
      // 根据角色计算不同的统计数据
      if (user.value?.role === 'logistics') {
        // 物流用户：统计物流相关的批次
        stats.value.logistics = batchStats.byStatus?.logistics || 0
      } else if (user.value?.role === 'merchant') {
        // 商家用户：统计销售相关的批次
        stats.value.sales = batchStats.byStatus?.sales || 0
      }
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 使用模拟数据作为后备
    if (user.value?.role === 'farmer') {
      stats.value.batches = Math.floor(Math.random() * 20) + 5
    } else if (user.value?.role === 'logistics') {
      stats.value.logistics = Math.floor(Math.random() * 15) + 10
    } else if (user.value?.role === 'merchant') {
      stats.value.sales = Math.floor(Math.random() * 25) + 8
    }
  }
}

// 初始化
onMounted(() => {
  loadRecentBatches()
  loadStats()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  min-height: calc(100vh - 60px);
}

.welcome-section {
  margin-bottom: 20px;
}

.welcome-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-info h2 {
  color: white;
  margin: 0 0 8px 0;
  font-size: 24px;
}

.welcome-desc {
  color: rgba(255, 255, 255, 0.9);
  margin: 8px 0;
  font-size: 14px;
}

.welcome-time {
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
  font-size: 13px;
}

.welcome-avatar {
  flex-shrink: 0;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-card {
  height: 100%;
}

.stats-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stats-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  flex-shrink: 0;
}

.stats-info {
  flex: 1;
}

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #7f8c8d;
  margin-top: 4px;
}

.quick-actions-section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.card-header .el-button {
  margin-left: auto;
}

.quick-action-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.quick-action-item:hover {
  background-color: #f8f9fa;
}

.action-icon {
  width: 40px;
  height: 40px;
  background: #f0f2f5;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409eff;
  font-size: 18px;
  flex-shrink: 0;
}

.action-content h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
}

.action-content p {
  margin: 0;
  font-size: 12px;
  color: #7f8c8d;
}

.activity-section {
  margin-bottom: 20px;
}

.empty-state {
  padding: 20px;
  text-align: center;
}

.batch-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.batch-item:last-child {
  border-bottom: none;
}

.batch-item:hover {
  background-color: #f8f9fa;
  margin: 0 -16px;
  padding-left: 16px;
  padding-right: 16px;
  border-radius: 4px;
}

.batch-info {
  flex: 1;
}

.batch-name {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.batch-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.batch-variety {
  font-size: 12px;
  color: #7f8c8d;
}

.batch-time {
  font-size: 12px;
  color: #bbb;
}

.batch-arrow {
  color: #c0c4cc;
  font-size: 14px;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-content {
  flex: 1;
}

.notification-title {
  font-weight: 500;
  color: #2c3e50;
  margin-bottom: 4px;
}

.notification-desc {
  font-size: 13px;
  color: #7f8c8d;
  margin-bottom: 4px;
  line-height: 1.4;
}

.notification-time {
  font-size: 12px;
  color: #bbb;
}

.notification-badge {
  flex-shrink: 0;
  margin-top: 2px;
}

.charts-section {
  margin-bottom: 20px;
}

.status-chart {
  padding: 16px 0;
}

.status-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.status-item:last-child {
  margin-bottom: 0;
}

.status-bar {
  width: 60%;
  height: 8px;
  background-color: #f0f2f5;
  border-radius: 4px;
  margin-right: 12px;
  overflow: hidden;
}

.status-progress {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.status-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;
}

.status-name {
  font-size: 14px;
  color: #606266;
}

.status-count {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
}

.workspace {
  padding: 16px 0;
}

.workspace-section {
  margin-bottom: 24px;
}

.workspace-section:last-child {
  margin-bottom: 0;
}

.workspace-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #909399;
  font-weight: 500;
}

.workspace-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.workspace-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #f0f0f0;
}

.workspace-item:hover {
  background-color: #f8f9fa;
  border-color: #409eff;
  color: #409eff;
}

.workspace-item .el-icon {
  font-size: 16px;
  color: #909399;
  transition: color 0.3s;
}

.workspace-item:hover .el-icon {
  color: #409eff;
}

.workspace-item span {
  font-size: 14px;
  color: #606266;
  transition: color 0.3s;
}

.workspace-item:hover span {
  color: #409eff;
}

/* 响应式 */
@media (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
  }
  
  .welcome-content {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .stats-section :deep(.el-col) {
    margin-bottom: 12px;
  }
  
  .quick-action-item {
    flex-direction: column;
    text-align: center;
    padding: 20px 16px;
  }
  
  .action-content h4 {
    margin-top: 8px;
  }
}
</style>